<template>
    <el-dialog :title="dialogTitle" :close-on-click-modal="false" :visible.sync="visible" @close="onDialogClose"
        width="500px">
        <el-form :model="commentForm" :rules="commentRules" ref="commentForm" label-width="100px">
            <el-form-item label="评论内容" prop="content">
                <el-input type="textarea" v-model="commentForm.content" :rows="4" placeholder="请输入您的评论"></el-input>
            </el-form-item>

            <el-form-item label="上传图片" prop="image">
                <file-upload tip="点击上传课程封面" action="" :auto-upload="false" :limit="1"
                    @change="ccommentImageUploadChange"></file-upload>
                <div class="el-upload__tip">只能上传 JPG/PNG 文件，且不超过 2MB</div>
            </el-form-item>

            <el-form-item label="星级评价" prop="rating">
                <el-rate v-model="commentForm.rating" :colors="['#99A9BF', '#F7BA2A', '#FF9900']" :max="5" show-text
                    text-color="#ff9900" :texts="['极差', '失望', '一般', '满意', '非常满意']"></el-rate>
            </el-form-item>

        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="visible = false">取消</el-button>
            <el-button type="primary" @click="submitComment()">提交评论</el-button>
        </span>
    </el-dialog>
</template>

<script>
export default {
    data() {
        return {
            visible: false,
            selectedFile: null,
            dialogTitle: '发表评论',
            commentForm: {
                id: null,           // 新增评论时为null
                courseId: null,    // 由父页面传入
                userId: null,      // 从 localStorage 获取
                content: '',        // 用户填写
                image: '',          // 用户上传
                rating: 0,          // 用户选择
                commentTime: null  // 后端生成
            },
            commentRules: {
                content: [
                    { required: true, message: '评论内容不能为空', trigger: 'blur' },
                    { min: 5, max: 500, message: '评论内容长度在 5 到 500 个字符', trigger: 'blur' }
                ],
                rating: [
                    { required: true, message: '请选择星级', trigger: 'change' },
                    { type: 'number', min: 1, message: '星级至少为1星', trigger: 'change' }
                ]
            },
            fileUploadUrl: '', // 文件上传的后端接口地址
            uploadHeaders: {}  // 文件上传请求头，例如包含Token
        };
    },
    methods: {
        init(courseId) {
            this.commentForm.id = null;
            this.commentForm.content = '';
            this.commentForm.image = '';
            this.commentForm.rating = 0;
            this.commentForm.commentTime = null; // 由后端生成

            this.visible = true;
            this.dialogTitle = '发表评论';

            this.commentForm.courseId = courseId; // 设置传入的 courseId

            // 获取当前用户ID
            const userId = localStorage.getItem('userId');
            this.commentForm.userId = userId ? parseInt(userId) : null;

            this.uploadHeaders = {
                'Token': localStorage.getItem('frontToken')
            };

            this.$nextTick(() => {
                this.$refs.commentFormRef.resetFields();
            });
        },
        ccommentImageUploadChange(file) {
            this.selectedFile = file;
        },
        submitComment() {
            this.$refs.commentForm.validate((valid) => {
                if (valid) {
                    const commentJsonString = JSON.stringify(this.commentForm);

                    const formData = new FormData();
                    formData.append('commentData', commentJsonString);
                    if (this.selectedFile) {
                        formData.append('image', this.selectedFile);
                    }

                    this.$http({
                        url: `comment/add`,
                        method: 'post',
                        body: formData,
                    }).then(({ data }) => {
                        this.dataListLoading = false;
                        if (data && data.code === 0) {
                            this.$message({
                                message: '操作成功',
                                type: 'success',
                                duration: 1500,
                                onClose: () => {
                                    this.addOrUpdateFlag = false;
                                    this.showFlag = true;
                                    this.$emit('refreshDataList');
                                    this.visible = false;
                                }
                            });
                        } else {
                            this.$message.error(data.msg || '操作失败');
                        }
                    }).catch(error => {
                        this.dataListLoading = false;
                        console.error("课程保存/更新接口错误:", error);
                        this.$message.error('请求失败，请稍后再试');
                    });
                }
            });
        },
        onDialogClose() {
            this.$emit('dialogClosed');
            this.$refs.commentFormRef.resetFields();
            this.commentForm = {
                id: null,
                course_id: null,
                user_id: null,
                content: '',
                image: '',
                rating: 0,
                comment_time: null
            };
        }
    }
};
</script>

<style>
/* 样式与之前相同，确保适用于评论上传器 */
.comment-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.comment-uploader .el-upload:hover {
    border-color: #409EFF;
}

.comment-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
}

.comment-image {
    width: 100px;
    height: 100px;
    display: block;
    object-fit: cover;
}
</style>